%% Author: Mamut
%% Created: 10.09.2006
%% Description: TODO: Add desciption to test
-module(test).

%%
%% Include files
%%

-include("./../include/janus.hrl"). 
-include_lib("xmerl/include/xmerl.hrl").


%%
%% Exported Functions
%%
-export([init/0, test/0, test2/0, test3/2, path/0]).

%%
%% API Functions
%%

init() ->
    sendSOAPRequest("http://rsdn.ru/ws/JanusAT.asmx").

test() ->
    A = #getForumList{forumRequest = #forumRequest{userName = {userName, "yo"}, password = {password, "yo2"}}},
    io:format("~p~n", [A]),
    orcas_soap_encoder:encode(A),
    orcas_soap_encoder:encode({getForumList, {attributes, [{"xmnls", "http://rsdn.ru/Janus/"}]}, {forumRequest, {userName, "yo"}, {password, "yo2"}}}).

test2() ->
    File = "E:/Mamut/PROJECTS/EclipseWorkspace/Orcas/varia/getForumListResponse.xml",
    orcas_soap_decoder:decode(File).

test3(UserName, Password) ->
    {},
	I = orcas_soap_decoder:decode(orcas_soap_client:request({"GetForumList", {attributes, [{"xmlns", "http://rsdn.ru/Janus/"}]}, {forumRequest, {userName, UserName}, {password, Password}}})),
    orcas_tools:save_to_file("E:/erllog.txt", I).

path() ->
    %filename:absname("./../varia/service.xsd").
    filename:module_info(test).
%%
%% Local Functions
%%

sendSOAPRequest(URL) ->
    
    % This part requests forum list firectly from RSDN%
    
    %
    % Call fails if we don't accept cookies
    %
    %http:set_options([{cookies, enabled}]),
    ibrowse:start_link(),
    io:format("~s~n", [getSOAPMessage()]),
    {ok, Status, ResponseHeaders, ResponseBody} = 
    ibrowse:send_req("http://rsdn.ru/ws/JanusAT.asmx", [{"SOAPAction", "\"http://rsdn.ru/Janus/GetForumList\""}], post, getSOAPMessage(), [{trace, true}, {content_type, "text/xml; charset=utf-8"}])
	
    
    %{ok, {{Version, _, ReasonPhrase}, Headers, Body}} = 
    %        http:request(post, {URL, [{"SOAPAction", "\"http://rsdn.ru/Janus/GetForumList\""}], "text/xml; charset=utf-8", getSOAPMessage()}, [], [])
	%,

    %
    % Here we read a previously obtained request from an XML file.
    % Useful for local testing.
    %
    %Body = "E:/Mamut/PROJECTS/EclipseWorkspace/Orcas/varia/getForumListResponse.xml",

    %{Doc, _} = xmerl_scan:file(Body),

    %A = xmerl_xpath:string("/soap:Envelope/soap:Body/GetForumListResponse/GetForumListResult/forumList/JanusForumInfo", Doc),
    %getForumList(A)%,
    %{}
    .

getSOAPMessage() ->    
		xmlProlog() ++ 
		envelopeStart() ++ 
		tagStart("soap:Body") ++ 
        tagStart("GetForumList", [{"xmnls", "http://rsdn.ru/Janus/"}]) ++
        tagStart("forumRequest") ++
        tagStart("userName") ++
        %
        % Replace *** with your RSDN login
        %
        "dmitriid" ++ 
        tagEnd("userName") ++
        tagStart("password") ++
        %
        % Replace *** with your RSDN password
        %
        "***" ++
       	tagEnd("password") ++
        tagEnd("forumRequest") ++
        tagEnd("GetForumList") ++
       	tagEnd("soap:Body") ++ 
        envelopeEnd()
                        .

xmlProlog() ->
	"<?xml version=\"1.0\" encoding=\"utf-8\"?>".

envelopeStart() ->
    tagStart("soap:Envelope", [{"xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"},
                               {"xmlns:xsd", "http://www.w3.org/2001/XMLSchema"},
                               {"xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/"}]).

envelopeEnd() ->
    tagEnd("soap:Envelope").

tagStart(F) ->
    tagStart(F, []).
tagStart(F, X) when X == []->
        "<" ++ F ++ ">";
tagStart(F, X)->
    "<" ++ F ++ " " ++ attributes(X) ++ ">".

attributes([{N, V}|L]) ->
    N ++ "=\"" ++ V ++ "\" " ++ attributes(L);
attributes([]) ->
    [].

tagEnd(F)->
    "</" ++ F ++ ">".



getForumList([H|L]) ->
    getForumInfo(H) ++ getForumList(L);
getForumList([]) ->
	[].    

getForumInfo(#xmlElement{content = C}) ->
    XmlElements = [ X || X <- C,
        				 element(1, X) == xmlElement],
    %
    % Horrible, horrible list comprehension.
    % Somebody, poke out my eyes!
    %
    ForumID = findElement(forumId, XmlElements)%,
	% [X || ]
    % [#janusForumInfo{	
    % 	forumID = textOf(ForumId), 
    %    forumGroupID = textOf(ForumGroupId), 
    %    shortForumName = textOf(ShortForumName), 
    %    forumName = textOf(ForumName), 
    %    rated = textOf(Rated), 
    %    inTop = textOf(InTop), 
    %    rateLimit = textOf(RateLimit)
    % } ||                        
	%	  ForumId <- XmlElements,
	%	  ForumGroupId <- XmlElements,
	%	  ShortForumName <- XmlElements,
    %     ForumName <- XmlElements,
    %      Rated <- XmlElements,
	%	  InTop <- XmlElements,
    %      RateLimit <- XmlElements,
    %      element(2, ForumId) == forumId,
    %      element(2, ForumGroupId) == forumGroupId,
    %      element(2, ShortForumName) == shortForumName,
    %      element(2, ForumName) == forumName,
    %      element(2, Rated) == rated,
    %      element(2, InTop) == inTop,
    %      element(2, RateLimit) == rateLimit
	%]
    .

findElement(Name, Elements) ->
	[X || X <- Elements, element(2, X) == Name].

%
% This function is available at 
% http://wiki.trapexit.org/index.php/How_to_write_an_RSS_aggregator
%
textOf(Item) ->
    lists:flatten([X#xmlText.value || X <- Item#xmlElement.content,
				      element(1,X) == xmlText]).